package com.wn.search.utils

import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.tencent.mmkv.MMKV
import com.wn.common.constant.SEARCH_HISTORY_INFO

/**
 * @Author: wn
 * @Date: 2024/12/17 16:52
 * @Description: 搜索管理类 -- 直接获取 MMKV ，encode 添加 ，decodeString 获取
 */
object SearchManager {
  /**
   * 直接获取 mmkv
   */
  private val mmkv = MMKV.defaultMMKV()

  /**
   * 保存搜索历史 -- 字符串列表
   * @param searchList
   */
  fun saveSearchHistory(searchList: MutableList<String>) {
    val histories = getSearchHistory() ?: mutableListOf()
    histories.addAll(searchList)
    val duplicateRemoval = histories.distinct() // 去重
    mmkv.encode(SEARCH_HISTORY_INFO, GsonUtils.toJson(duplicateRemoval))
  }

  /**
   * 添加搜索历史 -- 单一字符串
   * @param keyWord
   */
  fun addSearchHistory(keyWord: String) {
    val histories = getSearchHistory() ?: mutableListOf()
    histories.add(keyWord)
    val duplicateRemoval = histories.distinct()
    mmkv.encode(SEARCH_HISTORY_INFO, GsonUtils.toJson(duplicateRemoval))
  }

  /**
   * 获取搜索历史
   * @return MutableList
   */
  fun getSearchHistory(): MutableList<String>? {
    /**
     * 1 单一实体对象         GsonUtils.fromJson(str, Person::class.java)
     * 2 对象列表或者其他结构  GsonUtils.fromJson(str, object : TypeToken<MutableList<VideoInfo>>() {}.type)
     */
    val type = object : TypeToken<MutableList<String>>() {}.type
    return GsonUtils.fromJson(mmkv.decodeString(SEARCH_HISTORY_INFO), type)
  }

  /**
   * 清除搜索历史数据
   */
  fun clearSearchHistory() {
    mmkv.encode(SEARCH_HISTORY_INFO, "")
  }
}